package cn.longwingstech.intelligence.agent.app;

import cn.longwingstech.intelligence.agent.app.config.AiConfigProperties;
import cn.longwingstech.intelligence.agent.app.tool.PDFGenerationTool;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.HashSet;
import java.util.List;

@Slf4j
@Component
@Data
public class SuperApp {

    private final ChatClient chatClient;

    public SuperApp(AiConfigProperties aiConfigProperties) {
        OpenAiApi openAiApi = OpenAiApi.builder()
                .baseUrl(aiConfigProperties.getBaseUrl())
                .apiKey(aiConfigProperties.getApiKey())
                .build();

        OpenAiChatOptions options = OpenAiChatOptions.builder()
                .streamUsage(true)
                .model(aiConfigProperties.getModel())
                .build();

        OpenAiChatModel openAiChatModel = OpenAiChatModel.builder()
                .openAiApi(openAiApi)
                .defaultOptions(options)
                .build();

        chatClient = ChatClient.builder(openAiChatModel)
                .defaultSystem("你是超级智能体,可以调用很多工具")
                .defaultTools(new PDFGenerationTool())
                .build();
    }

    public Flux<String> chat(String message) {
        HashSet<String> set = new HashSet<>();
        Flux<ChatResponse> chatResponseFlux = chatClient.prompt().user(message)
                .stream().chatResponse();

        return chatResponseFlux.mapNotNull(chatResponse -> {
            Generation result = chatResponse.getResult();
            if (result==null) {
                return null;
            }
            List<AssistantMessage.ToolCall> toolCalls = result.getOutput().getToolCalls();
            System.err.println(toolCalls.isEmpty());
            return chatResponse.getResult().getOutput().getText();
        });
    }
}
